<?php

namespace app\api\controller\port;

use app\common\controller\Api;

use think\Exception;
use addons\epay\library\Service;
use app\common\model\Order as OrderModel;

/**
 * 回调接口
 */
class Notify extends Api
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = ['*'];

    
    /**
     * 微信支付回调
     * 
     */
    public function wxnotify()
    {
        $pay = Service::checkNotify('wechat');
        if (!$pay) return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);

        $data = $pay->verify();

        $fp = fopen('./wxlog.txt', 'a+');   //public/log.txt
        fwrite($fp, var_export('-------------22222', true));
        fwrite($fp, var_export($data, true));
        fwrite($fp, var_export('-------------|||', true));
        fclose($fp);

        try {
            db()->startTrans();

            // trace($data);
            //获取支付金额、订单号
            $payamount = $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            trace("回调成功，订单号：{$out_trade_no}，金额：{$payamount}，微信支付单号：{$data['transaction_id']}");

            $Model = new OrderModel();
            $orderOne = $Model->get(['order_sn'=>$out_trade_no]);

            //减去当前班次余票
            db('line_banc')->where('id',$orderOne->banc_id)->setDec('ticket_num',$orderOne->ticket_num);

            $qrcode = $this->buildQrcode($orderOne->id,$out_trade_no);
            $orderOne->save([
                'status' => 1,
                'qrcode' => $qrcode,
                'transaction_id'=>$data['transaction_id']
            ]);

            db()->commit();
        } catch (Exception $e) {
            trace("回调逻辑处理错误:" . $e->getMessage(), "error");
            db()->rollback();
        }

        return $pay->success()->send();
    }

    public function test()
    {
        $url = $this->buildQrcode(3,'CVDBFOP20240907163200');
        $url = cdnurl($url,true);
        $this->success('Success',$url);
    }
    
    //创建订单核销码
    private function buildQrcode($oid,$order_sn)
    {
        // $config = ['format' => 'png'];
        $config = get_addon_config('qrcode');
        // 写入到文件
        $qrcodePath = ROOT_PATH . 'public/qrcode/';
        $filename = "user_O_$oid";
        $filePath = $qrcodePath . "$filename.{$config['format']}";
        if (!file_exists($filePath)) {
            $params = [];
            $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));
            $params['text'] = $order_sn;

            $qrCode = \addons\qrcode\library\Service::qrcode($params);

            $qrCode->writeFile($filePath);
        }

        // $url = 'http://' . request()->host() . "/qrcode/$filename.{$config['format']}";
        $url = "/qrcode/$filename.{$config['format']}";
        return $url;
    }

    

}
